<template>
  <div class="courses-container">
    <div class="courses-header">
      <h1>探索课程</h1>
  
    </div>

    <!-- 搜索和筛选 -->
    <div class="filter-container">
      <div class="search-box">
        <el-input
          v-model="searchQuery"
          placeholder="搜索课程..."
          clearable
          @keyup.enter="handleSearch"
          :prefix-icon="Search"
        >
          <template #append>
            <el-button @click="handleSearch">搜索</el-button>
          </template>
        </el-input>
      </div>
      
      <div class="filter-options">
        <el-select
          v-model="selectedCategory"
          placeholder="课程分类"
          clearable
          @change="handleCategoryChange"
        >
          <el-option
            v-for="item in categories"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
        
        <el-select
          v-model="selectedDifficulty"
          placeholder="难度级别"
          clearable
          @change="fetchCourses"
        >
          <el-option label="初级" value="初级" />
          <el-option label="中级" value="中级" />
          <el-option label="高级" value="高级" />
        </el-select>
      </div>
    </div>

    <!-- 课程列表 -->
    <el-card class="course-list-container" v-loading="loading">
      <div v-if="courses.length === 0 && !loading" class="empty-state">
        <el-empty description="没有找到匹配的课程">
          <el-button @click="resetFilters">重置筛选条件</el-button>
        </el-empty>
      </div>

      <div v-else class="course-grid">
        <div v-for="course in courses" :key="course.id" class="course-item">
          <CourseCard :course="course" />
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination" v-if="total > 0">
        <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          :page-sizes="[12, 24, 36, 48]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          @update:current-page="currentPage = $event"
          @update:page-size="pageSize = $event"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'
import CourseCard from '@/components/frontend/CourseCard.vue'

const route = useRoute()
const router = useRouter()

// 状态变量
const loading = ref(false)
const courses = ref([])
const total = ref(0)
const categories = ref([])
const currentPage = ref(1)
const pageSize = ref(12)
const searchQuery = ref('')
const selectedCategory = ref(null)
const selectedDifficulty = ref(null)

// 获取课程分类列表
const fetchCategories = async () => {
  loading.value = true
  try {
    await request.get('/category/all', {}, {
      showDefaultMsg: false,
      onSuccess: (data) => {
        categories.value = data
      },
      onError: (error) => {
        console.error('获取分类列表失败:', error)
        ElMessage.error('获取分类列表失败')
      }
    })
  } catch (error) {
    console.error('获取分类列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取课程列表
const fetchCourses = async () => {
  loading.value = true
  
  try {
    // 如果选择了分类
    if (selectedCategory.value) {
      // 使用分类API
      await request.get(`/course/category/${selectedCategory.value}`, {}, {
        showDefaultMsg: false,
        onSuccess: (data) => {
          // 确保 data 是数组
          let filteredResults = Array.isArray(data) ? data : [];
          
          // 如果返回的不是数组，记录错误
          if (!Array.isArray(data)) {
            console.error('API 返回的数据格式不正确，预期是数组:', data);
          }
          
          // 按难度筛选
          if (selectedDifficulty.value) {
            filteredResults = filteredResults.filter(course => 
              course.difficulty === selectedDifficulty.value
            )
          }
          
          // 按搜索词筛选
          if (searchQuery.value) {
            const query = searchQuery.value.toLowerCase()
            filteredResults = filteredResults.filter(course => 
              course.title.toLowerCase().includes(query) || 
              (course.subtitle && course.subtitle.toLowerCase().includes(query)) ||
              (course.description && course.description.toLowerCase().includes(query))
            )
          }
          
          // 前端手动分页
          const startIndex = (currentPage.value - 1) * pageSize.value
          const endIndex = startIndex + pageSize.value
          
          total.value = filteredResults.length
          courses.value = filteredResults.slice(startIndex, endIndex)
        },
        onError: (error) => {
          console.error('获取分类课程失败:', error)
          ElMessage.error('获取分类课程失败')
        }
      })
    } else {
      // 构建请求参数
      const params = {
        pageNum: currentPage.value,
        pageSize: pageSize.value
      }
      
      // 添加搜索参数
      if (searchQuery.value) {
        params.search = searchQuery.value
      }
      
      // 添加难度筛选
      if (selectedDifficulty.value) {
        params.difficulty = selectedDifficulty.value
      }
      
      // 直接使用分页API
      await request.get('/course/page', params, {
        showDefaultMsg: false,
        onSuccess: (data) => {
          // 确保 data 和 data.records 存在
          if (data && data.records) {
            courses.value = data.records||[]
            total.value = data.total||0
          } else {
            console.error('API 返回的数据格式不正确:', data)
            courses.value = []
            total.value = 0
            ElMessage.error('获取课程数据格式有误')
          }
        },
        onError: (error) => {
          console.error('获取课程列表失败:', error)
          ElMessage.error('获取课程列表失败')
        }
      })
    }
    
    // 更新 URL 查询参数
    updateUrlParams()
  } catch (error) {
    console.error('获取课程列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  fetchCourses()
}

// 分类变更处理
const handleCategoryChange = () => {
  currentPage.value = 1
  fetchCourses()
}

// 分页大小变更
const handleSizeChange = (size) => {
  pageSize.value = size
  fetchCourses()
}

// 页码变更
const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchCourses()
}

// 重置筛选条件
const resetFilters = () => {
  searchQuery.value = ''
  selectedCategory.value = null
  selectedDifficulty.value = null
  currentPage.value = 1
  fetchCourses()
}

// 更新 URL 参数
const updateUrlParams = () => {
  const query = {}
  
  if (searchQuery.value) {
    query.search = searchQuery.value
  }
  
  if (selectedCategory.value) {
    query.category = selectedCategory.value
  }
  
  if (selectedDifficulty.value) {
    query.difficulty = selectedDifficulty.value
  }
  
  if (currentPage.value > 1) {
    query.page = currentPage.value
  }
  
  if (pageSize.value !== 12) {
    query.pageSize = pageSize.value
  }
  
  router.replace({ 
    path: route.path,
    query
  })
}

// 监听 URL 参数变化
watch(() => route.query, (newQuery) => {
  if (newQuery.search !== undefined) {
    searchQuery.value = newQuery.search || ''
  }
  
  if (newQuery.category !== undefined) {
    selectedCategory.value = newQuery.category ? Number(newQuery.category) : null
  }
  
  if (newQuery.difficulty !== undefined) {
    selectedDifficulty.value = newQuery.difficulty || null
  }
  
  if (newQuery.page !== undefined) {
    currentPage.value = Number(newQuery.page) || 1
  }
  
  if (newQuery.pageSize !== undefined) {
    pageSize.value = Number(newQuery.pageSize) || 12
  }
  
  // 避免重复加载
  if (Object.keys(newQuery).length > 0) {
    fetchCourses()
  }
}, { immediate: true })

// 生命周期钩子
onMounted(() => {
  // 从 URL 中获取查询参数
  if (route.query.search) {
    searchQuery.value = route.query.search
  }
  
  if (route.query.category) {
    selectedCategory.value = Number(route.query.category)
  }
  
  if (route.query.difficulty) {
    selectedDifficulty.value = route.query.difficulty
  }
  
  if (route.query.page) {
    currentPage.value = Number(route.query.page)
  }
  
  if (route.query.pageSize) {
    pageSize.value = Number(route.query.pageSize)
  }
  
  fetchCategories()
  fetchCourses()
})
</script>

<style lang="scss" scoped>
.courses-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.courses-header {
  text-align: center;
  margin-bottom: 30px;
  
  h1 {
    font-size: 2.5rem;
    color: var(--el-color-primary);
    margin-bottom: 10px;
  }
  
  .subtitle {
    font-size: 1.2rem;
    color: var(--el-text-color-secondary);
  }
}

.filter-container {
  margin-bottom: 24px;
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  align-items: center;
  justify-content: space-between;
  
  .search-box {
    flex: 1;
    min-width: 250px;
  }
  
  .filter-options {
    display: flex;
    gap: 12px;
    
    .el-select {
      min-width: 150px;
    }
  }
}

.course-list-container {
  min-height: 400px;
}

.course-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
  gap: 24px;
  margin-bottom: 24px;
}

.empty-state {
  padding: 40px 0;
  display: flex;
  justify-content: center;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

@media (max-width: 768px) {
  .filter-container {
    flex-direction: column;
    
    .search-box {
      width: 100%;
    }
    
    .filter-options {
      width: 100%;
    }
  }
  
  .course-grid {
    grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  }
}
</style> 